import Vue from 'vue'
import Vuex from 'vuex'
import {
  getAdminData,
  getGoodsList, login, getGoodsDetail, getAgentById, getAgent, updateUserStatus,
  getFinacial, getAgentByParams, getFinalByParams, byTimeSelectCashData, byTimeSelectOrderData,
  payCount,getNoticeList,deleteNoticeData
} from "../api/getData";
import {baseImgPath} from "../config/env";
import {setStore} from "../config/mUtils";

Vue.use(Vuex)

let vm = new Vue()
const state = {
  adminInfo: {

  },
  //商品列表
  goodsInfo: {
    activeIndex: '0',
    tableData: [],
    allTableData: [],
    limit: 10,
    currentPage: 1
  },
  loginInfo: {},
  //编辑中的商品信息
  editGoodsInfo: {
    formDatas: {
      productName: '',
      productPrice: '',
      primePrice: '',
      stockNum: '',
      points: '',
      ProductImages: '',
      moduleNumber: ''
    },
    mainImgArr: [],
    mainImg: '',
    detailImgArr: [],
    productId: '',
    detailImg: ''
  },
  //代理商信息
  agentInfo: {
    tableData: [],
    offset: 0,
    limit: 10,
    count: 0,
    currentPage: 1,
    allTableData: []
  },
  //编辑中的代理商信息
  editAgentInfo: {
    formDatas: {
      realname: '',
      IDnumber: '',
      address: '',
      user_id: '',
      user_type: '',
      rate: '',
      areaRate: '',
      agora: '',
      extend: '',
      help: '',
      subsidy: '',
      consume: '',
      spentMoney: '',
      integrals:''
    },
    range: {
      province: '',
      city: '',
      area: ''
    },
  },
  //财务报表
  finalInfo: {
    tableData: [],
    allTableData: [],
    limit: 10,
    currentPage: 1,
    date_value1: '',
    date_value2: '',
  },
  //财务统计
  finalCountInfo: {
    pickerOptions2: {
      shortcuts: [{
        text: '最近一周',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近三个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit('pick', [start, end]);
        }
      }]
    },
    date_value2: '',
    tableData: [],
    allTableData: [],
    currentPage: 1,
    limit: 10,
    thData:{
      ExtendSum: '',
      SumConsumeMoney: '',
      money: '',
      awaitJudge: '',
      judgeOver: '',
      serviceCharge: '',
      sumMarket: ''
    }
  },
  orderCountInfo: {
    date_value2: '',
    tableData: [],
    allTableData: [],
    currentPage: 1,
    limit: 10,
    orderSum: '',
    sumPayMoney: '',
    sumMarketPrice: '',
    sumPrimePrice: '',
    status2OrderSum: '',
    status3OrderSum: '',
  },
  payTypeCountInfo: {
    date_value2: '',
    tableData: [],
    allTableData: [],
    currentPage: 1,
    limit: 10,
    resData:{}
  },
  newsListInfo:{
    currentPage:1,
    limit:10,
    allTableData:[],
    tableData:[],
  },
  orderDispatchInfo:{
    selectInfo:''
  }
}

const mutations = {
  saveAdminInfo(state, adminInfo){
  	state.adminInfo = adminInfo;
  },

  setGoodsTabIndex(state, index) { //商品更换tab时的状态
    state.goodsInfo.activeIndex = index;
  },
  saveGoodsTable(state, tableInfo) { //保存 商品列表信息
    state.goodsInfo.allTableData = tableInfo;
   state.goodsInfo.currentPage = 1
    state.goodsInfo.tableData = vm.$_.chunk(tableInfo, state.goodsInfo.limit)[0]
  },
  changeGoodsList(state, val) { //商品分页、每页的数量改变数据
    state.goodsInfo.tableData = vm.$_.chunk(state.goodsInfo.allTableData, state.goodsInfo.limit)[val - 1]
  },
  saveLoginInfo(state, val) { //登录信息
    state.loginInfo = val;
  },
  //商品管理
  saveEditGoods(state, val) { //保存编辑商品的信息
    let curArr1 = []
    let curArr2 = []
    curArr1.push({name: '1', url: `${baseImgPath}CommodityImages/${val.ImageUrl[0]}`})
    state.editGoodsInfo.mainImgArr = curArr1
    state.editGoodsInfo.mainImg = val.ImageUrl[0] + ','

    let deArr = val.ImageUrl
    let {productDetails} = val
    deArr = deArr.splice(1)

    for (let item of deArr) { //预设详情图
      curArr2.push({
        name: '1', url: `${baseImgPath}CommodityImages/${item}`
      })
    }
    state.editGoodsInfo.formDatas=productDetails
    state.editGoodsInfo.detailImgArr = curArr2
    state.editGoodsInfo.productId = val.productId
    state.editGoodsInfo.detailImg = deArr.join(',')
    state.editGoodsInfo.formDatas.moduleNumber = productDetails.moduleNumber + ''
  },
  goodImgSuccess(state, val) { //商品编辑主图上传成功回调
    state.editGoodsInfo.mainImg = val.imagesName+','
  },
  goodDetailSuccess(state, val) { //详情图上传成功回调
    state.editGoodsInfo.detailImg = state.editGoodsInfo.detailImg + ',' + val.imagesName
  },
  removeEGoodsM(state, val) {//删除主图的回调
    state.editGoodsInfo.mainImg = ''
  },
  removeEGoodsD(state, val) {//删除详情图回调
    let detailImg = state.editGoodsInfo.detailImg
    let detStr = detailImg.substring(1)

    let arr5 = detStr.split(',')
    arr5.splice(val, 1)

    state.editGoodsInfo.detailImg = arr5.join(',')
  },
  //代理商
  saveAgentInfo(state, tableInfo) { //保存代理商信息
    state.agentInfo.allTableData = tableInfo;
    state.agentInfo.tableData = vm.$_.chunk(tableInfo, state.agentInfo.limit)[0]
    state.agentInfo.currentPage = 1
  },
  changeAgentList(state, params) {//代理商分页及每页显示数变化
    if (params.val) {
      state.agentInfo.tableData = vm.$_.chunk(state.agentInfo.allTableData, state.agentInfo.limit)[params.val - 1]
    }
    if (params.limit) {
      state.agentInfo.limit = params.limit
      state.agentInfo.tableData = vm.$_.chunk(state.agentInfo.allTableData, params.limit)[0]
      state.agentInfo.currentPage = 1
    }

  },
  saveUpdateAgentInfo(state, params) {
    vm.$set(state.agentInfo.tableData[params.index], 'status', params.status)
  }, //更新保存代理商状态
  saveEditAgent(state, val) {  //编辑代理商信息保存

    state.editAgentInfo.formDatas.user_id = val.user_id
    let result = val.result[0]

    state.editAgentInfo.formDatas=result
    let {user_type}=state.editAgentInfo.formDatas
    if(user_type==1){
      state.editAgentInfo.formDatas.user_type='省级代理'
    }
    if(user_type==2){
      state.editAgentInfo.formDatas.user_type='市级代理'
    }
    if(user_type==3){
      state.editAgentInfo.formDatas.user_type='县级代理'
    }
    if(user_type==4){
      state.editAgentInfo.formDatas.user_type='VIP代理'
    }
    if(user_type==5){
      state.editAgentInfo.formDatas.user_type='商务代理'
    }
    if(user_type==6){
      state.editAgentInfo.formDatas.user_type='体验代理'
    }
    state.editAgentInfo.range.province = result.address.split(',')[0]

    state.editAgentInfo.range.city = result.address.split(',')[1]
    state.editAgentInfo.range.area = result.address.split(',')[2]
  },
  changeAgentAddress(state, val) {  //代理商编辑地址改变回调
    state.editAgentInfo.formDatas.address = `${val.province.value},${val.city.value},${val.area.value}`
  },
  //财务报表
  saveFinal(state, val) {//保存财务报表信息
    state.finalInfo.allTableData = val
    state.finalInfo.tableData = vm.$_.chunk(val, state.finalInfo.limit)[0]
    state.finalInfo.currentPage = 1
  },
  changeFinalList(state, params) { //每页显示数和页码变化回调
    if (params.val) {
      state.finalInfo.tableData = vm.$_.chunk(state.finalInfo.allTableData, state.finalInfo.limit)[params.val - 1]
    }
    if (params.limit) {
      state.finalInfo.limit = params.limit
      state.finalInfo.tableData = vm.$_.chunk(state.finalInfo.allTableData, params.limit)[0]
      state.finalInfo.currentPage = 1
    }
  },
  //财务统计
  saveFinalCountInfo(state, val) { //财务统计列表数据
    for (let item of val.userData) {
      item.time = vm.$moment(item.time).format('YYYY-MM-DD')
    }
    state.finalCountInfo.allTableData = val.userData
    state.finalCountInfo.tableData = vm.$_.chunk(val.userData, state.finalCountInfo.limit)[0]
    state.finalCountInfo.currentPage = 1
    state.finalCountInfo.thData=val
  },
  finalCountCurPageChange(state, params) { //财务统计每页数和页码变化
    if (params.val) {
      state.finalCountInfo.tableData = vm.$_.chunk(state.finalCountInfo.allTableData, state.finalCountInfo.limit)[params.val - 1]
    }
    if (params.limit) {
      state.finalCountInfo.limit = params.limit
      state.finalCountInfo.tableData = vm.$_.chunk(state.finalCountInfo.allTableData, params.limit)[0]
      state.finalCountInfo.currentPage = 1
    }
  },
  //订单统计
  saveOrderCountInfo(state, val) { // 订单统计列表
    state.orderCountInfo.currentPage = 1
    state.orderCountInfo.allTableData = val.productList
    state.orderCountInfo.tableData = vm.$_.chunk(val.productList, state.orderCountInfo.limit)[0]
    state.orderCountInfo.orderSum = val.orderSum
    state.orderCountInfo.sumPayMoney = val.sumPayMoney
    state.orderCountInfo.sumMarketPrice = val.sumMarketPrice
    state.orderCountInfo.sumPrimePrice = val.sumPrimePrice
    state.orderCountInfo.status2OrderSum = val.status2OrderSum
    state.orderCountInfo.status3OrderSum = val.status3OrderSum
  },
  orderCountCurPageChange(state, params) { //订单每页数和页码数变化
    if (params.val) { //当前页码
      state.orderCountInfo.tableData = vm.$_.chunk(state.orderCountInfo.allTableData, state.orderCountInfo.limit)[params.val - 1]
    }
    if (params.limit) {
      state.orderCountInfo.limit = params.limit
      state.orderCountInfo.tableData = vm.$_.chunk(state.orderCountInfo.allTableData, params.limit)[0]
      state.orderCountInfo.currentPage = 1
    }
  },
  savePayTypeCountInfo(state, val) {
    state.payTypeCountInfo.resData=val
    state.payTypeCountInfo.allTableData=val.list
    for(let item of val.list){
      if(item.payWay==1){
        item.payWay='支付宝'
      }
      if(item.payWay==2){
        item.payWay='银行卡'
      }
      if(item.payWay==3){
        item.payWay='微信'
      }
    }
    state.payTypeCountInfo.tableData = vm.$_.chunk(val.list, state.payTypeCountInfo.limit)[0]
    state.payTypeCountInfo.currentPage = 1
  },
  payTypeCountCurPageChange(state, params) {
    if (params.val) {
      state.payTypeCountInfo.tableData = vm.$_.chunk(state.payTypeCountInfo.allTableData, state.payTypeCountInfo.limit)[params.val - 1]
    }
    if (params.limit) {
      state.payTypeCountInfo.limit = params.limit
      state.payTypeCountInfo.tableData = vm.$_.chunk(state.payTypeCountInfo.allTableData, params.limit)[0]
      state.payTypeCountInfo.currentPage = 1
    }
  },
  //消息列表
  saveNewsListInfo(state, res){
    for(let item of res){
      item.create_time=vm.$moment(item.create_time).format('YYYY-MM-DD h:mm:ss')
    }
    state.newsListInfo.allTableData = res
    state.newsListInfo.tableData = vm.$_.chunk(res, state.newsListInfo.limit)[0]
    state.newsListInfo.currentPage = 1
  },
  newsListPageChange(state,params){
    if (params.currentPage) { //当前页码
      state.newsListInfo.tableData = vm.$_.chunk(state.newsListInfo.allTableData, state.newsListInfo.limit)[params.currentPage - 1]
    }
    if (params.limit) {
      state.newsListInfo.limit = params.limit
      state.newsListInfo.tableData = vm.$_.chunk(state.newsListInfo.allTableData, params.limit)[0]
      state.newsListInfo.currentPage = 1
    }
  },
  deleteNewsListInfo(state,params){
    console.log(params)
    state.newsListInfo.tableData=state.newsListInfo.tableData.filter(item=>item.notice_id!=params)
  }
}
const getters = {
  filterGoods(state) {
    let val = state.goodsInfo.allTableData
    for (let item of val) {
      item.image = `${baseImgPath}/CommodityImages/${item.image}`
      if (item.points) {
        item.points = `${item.points.substr(0, 15)}...`
      }
    }
    return val
  }
}
const actions = {

  async getAdminInfo({commit},params){
    let res=await getAdminData(params)
    try {
      commit('saveAdminInfo', res);
    }catch (e) {
      throw new Error(e)
    }
  },
  async toLogin({commit}, data) {

    await login(data)
      .done(res => {
        if (res.success) {
          setStore('token', res.token)
          vm.$message({
            message: '登录成功！',
            type: 'success'
          });
          commit('saveLoginInfo', res);
        } else {
          vm.$message.error(`登录失败!`)
        }
      })
  },
  //商品管理
  async goodsList({commit}, data) {
    await getGoodsList(data)
      .done(res => {
        let val = res.productList
        for (let item of val) {
          item.image = `${baseImgPath}CommodityImages/${item.image}`
          if (item.points) {
            item.points = `${item.points.substr(0, 15)}...`
          }
        }
        val = val.filter(item => item.status != 3)
        commit('saveGoodsTable', val);
      })
  },
  async getEditGood({commit}, data) {
    await getGoodsDetail(data)
      .done(res => {
        commit('saveEditGoods', {...res, ...data});
      })
  },
  //代理商
  async getAgentList({commit}) {
    // console.log('11111111')
    await getAgent()
      .done(res => {
        if (res.message == 'success') {
          commit('saveAgentInfo', res.result);
        }
      })
  },  //获取代理商列表
  async getAgentListByQuery({commit}, data) {

    await getAgentByParams(data)
      .done(res => {
        if (res.message == 'success') {
          commit('saveAgentInfo', res.result);
        }
      })
  }, //根据条件查询代理商
  async upDateAgentInfo({commit}, params) {
    await updateUserStatus({user_id: params.user_id, status: params.status})
      .done(res => {
        if (res.message == 'success') {
          commit('saveUpdateAgentInfo', params);
          vm.$message({
            type: 'success',
            message: '修改成功'
          })
        }
      })
  }, //修改代理商状态
  async getEditAgent({commit}, data) {
    // console.log(JSON.stringify(data)+'____________')
    await getAgentById(data)
      .done(res => {
        commit('saveEditAgent', {...res, ...data});
      })
  }, //获取编辑代理商的信息
  //财务报表
  async getFinalList({commit}) {
    await getFinacial()
      .done(res => {
        commit('saveFinal', res.result);
      })
  }, //获取财务报表列表
  async getFinalListByQuery({commit}, data) {
    await getFinalByParams(data)
      .done(res => {
        if (res.message == 'success') {
          commit('saveFinal', res.result);
        }
      })
  }, //根据条件查询财务报表
  //财务统计
  async getFinalCountList({commit}, data) {
    await byTimeSelectCashData(data)
      .done(res => {
        commit('saveFinalCountInfo', res);
      })
  },
  //订单统计
  async getOrderCountList({commit}, data) {
    await byTimeSelectOrderData(data)
      .done(res => {
        commit('saveOrderCountInfo', res);
      })
  },
  //支付方式统计
  async getPayTypeCountList({commit}, data) {
    await payCount(data)
      .done(res=>{
        commit('savePayTypeCountInfo',res);
      })
  },
  //获取消息列表
  async getNewsList({commit}, data) {
    await getNoticeList()
      .done(res=>{
        commit('saveNewsListInfo',res.list);
      })
  },
//删除消息列表
  async deleteNoticeData({commit},data){
    let res= await deleteNoticeData(data)
    if(res.success==true){
      vm.$message({
        type:'success',
        message:'删除成功'
      })
      commit('deleteNewsListInfo',data.notice_id);
    }
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters
})
